// pages/productdetail/productdetail.js
// MENU ==> 是否为点击tab选项卡进行滚动的，如果是，则不需要再次设置内容的激活状态
let MENU = 0;
var WxParse = require('../../wxParse/wxParse.js');
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        imgUrls: [
            '../../uploadimg/goods-img.jpg',
            '../../uploadimg/goods-img.jpg',
            '../../uploadimg/goods-img.jpg'
        ],
        network:false,
        tab:['商品','参团','评价','详情'],
        tabindex:0,
        share:true,
        canvas:true,
        tips:true,
        assistant:true,
        service: true,
        select:null,
        num:1,
        group_id:null
    },

    /**
     * 生命周期函数--监听页面加载
     */
    // onLoad: function (options) {
    //     var param_id = options.id;
    //     /**判断是否是通过生成二维码扫码进来 */
    //     var scene = decodeURIComponent(options.scene);
    //     if (scene != 'undefined') {
    //         param_id = scene;
    //     }
    //     this.setData({
    //         activity_id: param_id
    //     });
    //     this.getActivity(param_id);
    //     this.wxCanvasToTempFilePath = wx.canvasToTempFilePath;
    //     this.wxSaveImageToPhotosAlbum = wx.saveImageToPhotosAlbum;
    // },

    onShow:function(){
        this.setData({
            userInfo: app.globalData.userInfo
        });
        var options = this.options;
        var param_id = options.id;
        /**判断是否是通过生成二维码扫码进来 */
        var scene = decodeURIComponent(options.scene);
        if (scene != 'undefined') {
            param_id = scene;
        }
        this.setData({
            activity_id: param_id
        });
        this.getActivity(param_id);
        this.wxCanvasToTempFilePath = wx.canvasToTempFilePath;
        this.wxSaveImageToPhotosAlbum = wx.saveImageToPhotosAlbum;
    },

    //显示服务
    showService:function(){
        this.setData({
            service:false
        });
    },

    //关闭服务
    closeServcie:function(){
        this.setData({
            service:true
        });
    },
    //参加拼团
    join:function(e){
        this.setData({
            group_id:e.currentTarget.id,
            assistant:false
        });
    },

    //点击开团-弹出规格
    buy:function(){
        this.setData({
            group_id:null,
            assistant:false
        });
    },

    //关闭规格
    closed:function(){
        this.setData({
            assistant:true
        });
    },

    //点击确定
    makesure:function(){
        //判断是否为多规格
        var flag = true;
        if(this.data.data.plans.length != 1){
            if(this.data.select == null){
                flag = false;
                wx.showToast({
                    title:'请选择规格',
                    icon:'none'
                });
            }
        }
        if(flag){
            //判断用户是否登录
            if(!this.data.userInfo){
                wx.navigateTo({
                    url: '../unAuth/unAuth',
                })
                return ;
            }
            //关闭弹框
            this.setData({
                assistant:true
            });
            //整理确定订单页面参数
            var param = {
                image: this.data.data.goods.image,
                name:this.data.data.goods.name,
                goods_id:this.data.data.goods.id,
                goods_info_id: this.data.data.plans[this.data.select].goods_info_id,
                assistant:this.data.data.plans[this.data.select].assistant,
                group_price: this.data.data.plans[this.data.select].group_price,
                leader_price: this.data.data.plans[this.data.select].leader_price,
                num:this.data.num,
                activity_id:this.data.data.activity.id,
                type:this.data.data.activity.type,
                is_support_coupon: this.data.data.activity.is_support_coupon,
                cut_money: this.data.data.activity.cut_money,
                postage_price: this.data.data.goods.postage_price
            };
            //存在团信息则带入团id
            if(this.data.group_id){
                param.group_id = this.data.group_id;
            }
            param = JSON.stringify(param);
            wx.navigateTo({
                url: '../submitorder/submitorder?param='+param,
            })
        }
    },

    //选择规格
    select:function(e){
        this.setData({
            select:e.currentTarget.id
        });
        var num = this.data.num;
        //判断购买数量是否超出当前选择的规格库存
        //获取该活动是否设置限购数量
        var limit = this.data.data.activity.limit;
        if (limit == 0) {
            if (num > this.data.data.plans[this.data.select].stock) {
                this.setData({
                    num: this.data.data.plans[this.data.select].stock
                });
            }
        } else {
            if (num  > limit) {
                this.setData({
                    num: limit
                });
            }
        }
    },
    //购买数量加
    numJiaTap:function(){
        var num = this.data.num;
        //获取该活动是否设置限购数量
        var limit = this.data.data.activity.limit;
        if(limit == 0){
            //多规格只判断是否选中的规格是否超过库存,若没有选中规格则不做判断
            if(this.data.data.plans.length == 1){
                if((num + 1) > this.data.data.plans[0].stock){
                    wx.showToast({
                        title: '库存不足',
                        icon: 'none'
                    });
                }else{
                    ++num;
                }
            }else{
                if(this.data.select != null){
                    if((num + 1) > this.data.data.plans[this.data.select].stock){
                        wx.showToast({
                            title: '库存不足',
                            icon: 'none'
                        });
                    }
                }else{
                    ++num;;
                }
            }
        }else{
            if(num + 1 > limit){
                wx.showToast({
                    title:'每个用户限购'+limit+'件',
                    icon:'none'
                });
            }else{
                ++num;
            }
        }
        this.setData({
            num: num
        });
    },
    //购买数量减
    numJianTap: function () {
        var num = this.data.num;
        if(num == 1){
            wx.showToast({
                title: '不能再减了',
                icon: 'none'
            });
        }else{
            --num;
        }
        this.setData({
            num: num
        });
    },

    //监听滑动swiper滑动事件
    change:function(e){
        var that = this;
        var current = e.detail.current;
        //判断是否存在视频
        if(that.videoContext != undefined){
            if(current == 0){
                that.videoContext.play();
            }else{
                that.videoContext.pause();
            }
        }
    },

    //获取数据
    getActivity:function(activity_id){
        var that = this;
        var data = {
            activity_id: activity_id
        };
        if(app.globalData.userInfo){
            data.user_id = app.globalData.userInfo.id;
        }
        app.common.apiRequest('api/activity/info',data,function(res){
            that.isCollect(activity_id);
            //判断是否为神秘团
            if(res.data.activity.type == 2){
                that.setData({
                    tab: ['商品', '评价', '详情'],
                });
            }
            //显示开团信息则对时间进行处理
            that.handleTime(res.data.end_times);
            that.setData({
                data:res.data,
                network:true
            });
            //如果是单规格则设置select为0
            if(res.data.plans.length == 1){
                that.setData({
                    select:0
                });
            }
            /*富文本处理 */
            WxParse.wxParse('article', 'html', res.data.goods.content, that, 5);
            //存在视频,获取视频组件
            if (that.data.data.goods.links.length) {
                that.videoContext = wx.createVideoContext('myVideo');
            }
            that.remarkHeight();
        })
    },

    //判断是否收藏
    isCollect: function (activity_id){
        if(this.data.userInfo){
            var that = this;
            var data ={
                user_id: this.data.userInfo.id,
                activity_id: activity_id
            }
            app.common.apiRequest('api/collect/isCollect',data,function(res){
                var flag = res.data.flag;
                that.setData({
                    isCollect: flag
                });
            })
        }else{
            this.setData({
                isCollect:false
            });
        }
    },

    //收藏或取消收藏
    collect:function(){
        if (!this.data.userInfo) {
            wx.showModal({
                title: '提示',
                content: '您尚未登录',
                showCancel:false
            })
        }else{
            var that = this;
            var data = {
                user_id:this.data.userInfo.id,
                activity_id: this.data.activity_id
            }
            app.common.apiRequest('api/collect/collectOrCancel',data,function(res){
                var isCollect = !that.data.isCollect;
                that.setData({
                    isCollect: isCollect
                });
            })
        }
    },

    //标记容器距离顶部距离
    remarkHeight: function () {
        var that = this;
        // 获取商品数组的位置信息
        wx.createSelectorQuery().selectAll('.height').boundingClientRect(function (rects) {
            var height = [];
            rects.forEach(function (rect, index) {
                height.push(rect.top);
                if(index == rects.length - 1){
                    that.setData({
                        height: height
                    });
                }
            })
        }).exec();
    },
    //监听页面滚动事件
    onPageScroll: function (e) {
        var that = this;
        var height = that.data.height;
        var scroll_top = e.scrollTop;
        that.setData({
            scroll_top:scroll_top
        });
        if(MENU == 0){
            for (let i = 0; i < height.length; i++) {
                if (scroll_top < height[i] && i !== 0 && scroll_top > height[i - 1]) {
                    return this.setDis(i)
                }
            }
            return this.setDis(0)
        } 
    },
    //tab选项卡切换事件
    tab:function(e){
        MENU = 1;
        var index = e.currentTarget.id;
        var tabindex = this.data.tabindex;
        if(index != tabindex){
            var height = this.data.height;
            if (wx.pageScrollTo) {
                wx.pageScrollTo({
                    scrollTop: height[index]
                });
            } else {
                wx.showModal({
                    title: '提示',
                    content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
                })
            }
            this.setDis(tabindex);
        }
    },
    //设置选中项
    setDis:function(e){
        this.setData({
            tabindex: e
        });
        MENU = 0;
    },

    //分享
    share:function(){
        this.setData({
            tips:false
        });
    },
    //关闭弹框
    closedTips:function(){
        this.setData({
            tips:true
        });
    },

    //生成图片
    createCanvas:function (){
        var that = this;
        that.setData({
            tips:true,
            canvas:false
        });
        var goods = that.data.data.goods;
        const ctx = wx.createCanvasContext('shareCanvas');
        //填充画布颜色
        ctx.setFillStyle('#FFFFFF')
        ctx.fillRect(0, 0, 307, 429)
        ctx.draw(true)
        wx.getImageInfo({
            src: goods.image,
            success:function(res){
                const ctx = wx.createCanvasContext('shareCanvas')
                //设置文字
                ctx.setFillStyle('#ff3242')  // 文字颜色：黑色
                ctx.setFontSize(16)         // 文字字号：22px
                ctx.fillText("￥"+that.data.data.plans[0].group_price, 15, 350)
                ctx.fillText(that.data.data.activity.num + '人团', 80, 350)
                ctx.draw(true)
                ctx.setFillStyle('#2a2a2a')
                ctx.setFontSize(12)
                ctx.fillText(goods.name, 15, 375)
                ctx.fillText(goods.remark, 15, 400)
                // 商品size
                const goodsSize = 307
                ctx.drawImage(res.path, 1, 0, goodsSize, goodsSize)
                wx.getImageInfo({
                    src: 'http://www.pingecai.com/uploads/code.jpeg',
                    success: function (r) {
                        console.log(r);
                        // 小程序码
                        const qrImgSize = 76
                        ctx.drawImage(r.path, 220, 327, qrImgSize, qrImgSize)
                        ctx.stroke()
                        ctx.draw(true)
                    }
                })
            }
        })
    },

    //取消
    cancel:function(){
        this.setData({
            canvas:true
        });
    },

    //保存图片
    saveFile:function(){
        wx.canvasToTempFilePath({
            canvasId: 'shareCanvas',
            success:function(res){
                wx.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success:function(){
                        wx.showToast({
                            title: '已保存到相册'
                        })
                    },
                    complete:function(e){
                        console.log(e);
                    }
                })
            }
        });
    },

    //时间处理
    handleTime(end_times) {
        let endTimeList = [];
        let actStatus = [];
        // 将活动的结束时间参数提成一个单独的数组，方便操作,活动状态都设置进行中状态
        end_times.forEach(o => {
            endTimeList.push(o);
            actStatus.push(true);
        })
        this.setData({
            actEndTimeList: endTimeList,
            actStatus: actStatus
        });
        // 执行倒计时函数
        this.countDown();
    },
    timeFormat(param) { //小于10的格式化函数
        return param < 10 ? '0' + param : param;
    },
    countDown() { //倒计时函数
        // 获取当前时间，同时得到活动结束时间数组
        let newTime = new Date().getTime();
        let endTimeList = this.data.actEndTimeList;
        let countDownArr = [];
        let actStatus = this.data.actStatus;
        // 对结束时间进行处理渲染到页面
        endTimeList.forEach((o, index) => {
            //计算时间戳方式二，（兼容ios和android）
            let arr = o.split(/[- :]/);
            let nndate = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]);
            nndate = Date.parse(nndate)
            let endTime = nndate;
            let obj = null;
            // 如果活动未结束，对时间进行处理
            if (endTime - newTime > 0) {
                let time = (endTime - newTime) / 1000;
                // 获取天、时、分、秒
                let day = parseInt(time / (60 * 60 * 24));
                let hou = parseInt(time % (60 * 60 * 24) / 3600);
                let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
                let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
                obj = {
                    day: this.timeFormat(day),
                    hou: this.timeFormat(hou),
                    min: this.timeFormat(min),
                    sec: this.timeFormat(sec)
                }
            } else { //活动已结束，全部设置为'00'
                obj = {
                    day: '00',
                    hou: '00',
                    min: '00',
                    sec: '00'
                }
                //剔除掉已过期的团
                var data = this.data.data;
                data.groups.splice(index,1);
                data.end_times.splice(index,1);
                this.setData({
                    data:data
                });
                this.handleTime(data.end_times);
            }
            countDownArr.push(obj);
        })
        // 渲染，然后每隔一秒执行一次倒计时函数
        this.setData({
            countDownList: countDownArr,
            actStatus: actStatus
        })
        setTimeout(this.countDown, 1000);
    },

    mygroup:function(){
        //判断用户是否登录
        if(!this.data.userInfo) {
            wx.navigateTo({
                url: '../unAuth/unAuth',
            })
            return;
        }
        wx.navigateTo({
            url: '../mygroup/mygroup',
        })
    }
    
})